package com.mars.component.scheduler.spring;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.utils.date.DateUtil;
import com.mars.component.scheduler.model.SchedulerJob;

public class ScheduleJobQuartz extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass()) ;
	
	//private ExecutorService service = Executors.newSingleThreadExecutor(); 
	
	@Override
	protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
		JobDataMap jobDataMap = ctx.getJobDetail().getJobDataMap() ;
		logger.debug("参数名称==>>"+ JSON.toJSON(jobDataMap.getKeys()));
		logger.debug("参数的值==>>"+ JSON.toJSON(jobDataMap.values()));
		
		//取得当前任务作业信息
		SchedulerJob schedulerJob = (SchedulerJob) ctx.getMergedJobDataMap().get(SchedulerJob.JOB_PARAM_KEY);
		
		//作业开始时间
        long startTime = System.currentTimeMillis();
		
        try {
            //执行作业
        	logger.info("作业准备执行  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression());
        	
            /*ScheduleRunnable task = new ScheduleRunnable(
            		schedulerJob.getBeanName(), 
            		schedulerJob.getMethodName(), 
            		schedulerJob.getParams());
            
            Future<?> future = service.submit(task);
            
			future.get();*/
			
			//作业执行总时长
			long times = System.currentTimeMillis() - startTime;
			
			logger.info("作业执行完毕  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression() + "  时间：" + DateUtil.getDateTime() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			//作业执行总时长
			long times = System.currentTimeMillis() - startTime;
			
			logger.error("作业执行失败  ==>  作业名称：" + schedulerJob.getJobName() + "  作业ID：" + schedulerJob.getJobId() + "  分组名称：" + schedulerJob.getJobGroup() + "  Cron表达式：" + schedulerJob.getCronExpression() + "  时间：" + DateUtil.getDateTime() + "  总共耗时：" + times + "毫秒 ", e);
		} finally {
			//记录作业的执行信息到数据库
		}
		
	}

}
